package logic

import (
	"context"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"srv/course"
	"srv/internal/svc"
	"srv/models/mysql"
	"srv/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *course.CreateOrderRequest) (*course.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.Info(int(in.GoodsId))
	if err != nil {
		logx.Error("商品不存在")
		return nil, err
	}
	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足")
		return nil, err
	}
	orderSn := uuid.NewString()
	amount := g.GoodsPrice * float64(in.Num)
	o := mysql.Order{
		Model:    gorm.Model{},
		UserId:   int(in.UserId),
		OrderSn:  orderSn,
		PayType:  int(in.PayType),
		PayState: 1,
		PayTime:  0,
		Amount:   amount,
	}
	err = o.Create()
	if err != nil {
		logx.Error("创建订单表失败")
		return nil, err
	}
	//totalAmount := string(amount)
	alipay := pkg.AliPay{
		Subject:     "商品标题",
		OutTradeNo:  orderSn,
		TotalAmount: "",
	}
	url := alipay.Pay()
	return &course.CreateOrderResponse{
		PayUrl:  url,
		OrderId: int64(o.ID),
	}, nil
}
